package com.wodsy.comtroller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.wodsy.bean.FreightTempDestinationVo;
import com.wodsy.bean.FreightTempSubVo;
import com.wodsy.phoenix.dataobject.base.Pager;
import com.wodsy.phoenix.dataobject.base.PhoenixGenericResponse;
import com.wodsy.phoenix.dataobject.base.PhoenixResponseWrapper;
import com.wodsy.phoenix.dataobject.shopc.model.*;
import com.wodsy.phoenix.dataservice.shopc.service.FreightTempService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Huang on 2015/5/14.
 */
@Controller
@RequestMapping(value = "/freight")
public class FreightTempController {

    @Reference(interfaceClass = FreightTempService.class,interfaceName="com.wodsy.phoenix.dataservice.shopc.service.FreightTempService")
    private FreightTempService freightTempService;

    @RequestMapping(value = { "/list/{pageNo}" }, method = RequestMethod.GET)
    public String list(@PathVariable Integer pageNo,Map<String, Object> model) {
        if(pageNo == null || pageNo < 1){
            pageNo = 1;
        }
        Pager<FreightTemp> pager = new Pager<FreightTemp>();
        pager.setPageNo(pageNo);
        //TODO 获取userId shopId
        PhoenixResponseWrapper<FreightTemp> wrapper = freightTempService.findFreightTempsByOwnerInfo(pager, 2, 1);
        model.put("pager",wrapper.getPager());
        return "freighttemp/freightindex";
    }

    @RequestMapping(value = { "/toAdd" }, method = RequestMethod.GET)
    public String toAdd(Map<String, Object> model) {
        // model.put("testName",testService.getName());
        PhoenixResponseWrapper<FreightTempPriceUnit> priceUnitWrapper = freightTempService.findFreightTempPriceUnit();
        List<FreightTempPriceUnit> priceUnits = priceUnitWrapper.getPager().getItems();
        model.put("priceUnits",priceUnits);

        PhoenixResponseWrapper<FreightTempDeliveryMethod> methodWrapper = freightTempService.findFreightTempDeliveryMethod();
        List<FreightTempDeliveryMethod> deliveryMethods = methodWrapper.getPager().getItems();
        model.put("deliveryMethods",deliveryMethods);

        return "freighttemp/newfreighttemp";
    }

    @RequestMapping(value = { "/add" }, method = RequestMethod.POST)
    public String add(String name,Boolean isFree,Integer priceUnit,String jsonStr) {
        FreightTemp freightTemp = new FreightTemp();
        freightTemp.setName(name);
        freightTemp.setIsFree(isFree);
        if(priceUnit == null){
            freightTemp.setPriceUnit(null);
        }else if(priceUnit > 0){
            PhoenixResponseWrapper<FreightTempPriceUnit> priceUnitWrapper = freightTempService.getFreightTempPriceUnit(priceUnit);
            freightTemp.setPriceUnit(priceUnitWrapper.getObj());
        }

        jsonSetToFreightTemp(jsonStr, freightTemp);
        //TODO 获取userId shopId
        freightTemp.setUserId(1);
        freightTemp.setShopId(2);
        freightTempService.addFreightTemp(freightTemp);
        return "redirect:/freight/list/1";
    }

    @RequestMapping(value = { "/copy/{tempId}" }, method = RequestMethod.POST)
    @ResponseBody
    public String copy(@PathVariable Integer tempId){
        PhoenixResponseWrapper<FreightTemp> wrapper = freightTempService.getFreightTemp(tempId);
        if (wrapper.isOK()){
            FreightTemp source = wrapper.getObj();
            FreightTemp target = new FreightTemp();
            BeanUtils.copyProperties(source, target);
            target.setId(null);
            target.setName(source.getName()+" 副本");
            Set<FreightTempSub> freightTempSubs = target.getFreightTempSubs();
            if (freightTempSubs != null && !freightTempSubs.isEmpty()) {
                for (FreightTempSub sub : freightTempSubs) {
                    sub.setId(null);
                    Set<FreightTempDestination> destinations = sub.getDestinations();
                    for (FreightTempDestination destination : destinations) {
                        destination.setId(null);
                        destination.setFtsId(null);
                        Set<FreightTempArea> areas = destination.getAreas();
                        for (FreightTempArea area : areas) {
                            area.setId(null);
                            area.setFtdId(null);
                        }
                    }
                }
            }
            freightTempService.addFreightTemp(target);
            return "ok";
        }
        return "err";
    }

    @RequestMapping(value = { "/del/{tempId}" }, method = RequestMethod.POST)
    @ResponseBody
    public String del(@PathVariable Integer tempId){
        //TODO 判断是否有商品在使用此模板
        PhoenixResponseWrapper<PhoenixGenericResponse> wrapper = freightTempService.delFreightTemp(tempId);
        if (wrapper.isOK()){
            return "ok";
        }
        return "err";
    }

    @RequestMapping(value = { "/toUpdate/{tempId}" }, method = RequestMethod.GET)
    public String toUpdate(@PathVariable Integer tempId,Map<String, Object> model) {
        PhoenixResponseWrapper<FreightTemp> wrapper = freightTempService.getFreightTemp(tempId);
        FreightTemp temp = wrapper.getObj();
        model.put("temp",temp);

        PhoenixResponseWrapper<FreightTempDeliveryMethod> methodWrapper = freightTempService.findFreightTempDeliveryMethod();
        List<FreightTempDeliveryMethod> deliveryMethods = methodWrapper.getPager().getItems();
        model.put("deliveryMethods",deliveryMethods);
        return "freighttemp/editfreighttemp";
    }

    @RequestMapping(value = { "/update/{tempId}" }, method = RequestMethod.POST)
    public String update(@PathVariable Integer tempId,String name,Boolean isFree,Integer priceUnit,String jsonStr) {
        FreightTemp freightTemp = new FreightTemp();
        freightTemp.setId(tempId);
        freightTemp.setName(name);
        freightTemp.setIsFree(isFree);
        if(priceUnit == null){
            freightTemp.setPriceUnit(null);
        }else if(priceUnit > 0){
            PhoenixResponseWrapper<FreightTempPriceUnit> priceUnitWrapper = freightTempService.getFreightTempPriceUnit(priceUnit);
            freightTemp.setPriceUnit(priceUnitWrapper.getObj());
        }
        jsonSetToFreightTemp(jsonStr,freightTemp);
        //TODO 获取userId shopId
        freightTemp.setUserId(1);
        freightTemp.setShopId(2);
        freightTempService.mergeFreightTemp(freightTemp);
        return "redirect:/freight/list/1";
    }

    private void jsonSetToFreightTemp(String jsonStr,FreightTemp freightTemp){
        if (jsonStr != null && !jsonStr.isEmpty()){
            HashSet<FreightTempSub> freightTempSubs = new HashSet<FreightTempSub>();
            JSONArray jsonArray = JSONArray.fromObject(jsonStr);
            Iterator iterator = jsonArray.iterator();
            while (iterator.hasNext()){
                Object next = iterator.next();
                JSONObject jsonObject = JSONObject.fromObject(next);
                Map<String,Class> map = new HashMap<String,Class>();
                map.put("destinations",FreightTempDestinationVo.class);
                FreightTempSubVo subVo = (FreightTempSubVo) JSONObject.toBean(jsonObject,FreightTempSubVo.class,map);

                PhoenixResponseWrapper<FreightTempDeliveryMethod> methodWrapper = freightTempService.getFreightTempDeliveryMethod(subVo.getDeliveryMethodId());
                FreightTempSub freightTempSub = new FreightTempSub();
                freightTempSub.setDeliveryMethod(methodWrapper.getObj());
                freightTempSub.setInRange(subVo.getInRange());
                freightTempSub.setInRangePrice((int)(subVo.getInRangePrice()*100.0));
                freightTempSub.setOutRangeWeight(subVo.getOutRangeWeight());
                freightTempSub.setOutRangePrice((int)(subVo.getOutRangePrice()*100.0));

                Set<FreightTempDestination> destinations = new HashSet<FreightTempDestination>();
                if (subVo.getDestinations() != null && !subVo.getDestinations().isEmpty()){
                    for(FreightTempDestinationVo destinationVo : subVo.getDestinations()){
                        FreightTempDestination destination = new FreightTempDestination();
                        destination.setOutRangePrice((int)(destinationVo.getOutRangePrice()*100.0));
                        destination.setInRangePrice((int)(destinationVo.getInRangePrice()*100.0));
                        destination.setInRange(destinationVo.getInRange());
                        destination.setOutRangeWeight(destinationVo.getOutRangeWeight());

                        Set<FreightTempArea> areas = new HashSet<FreightTempArea>();
                        String[] areaStrs = destinationVo.getAreas().split(",");
                        String[] areaNames = destinationVo.getAreaNames().split("/");
                        for(int i=0 ;i< areaStrs.length; i++){
                            String areaId = areaStrs[i];
                            FreightTempArea area = new FreightTempArea();
                            area.setAreaId(Integer.parseInt(areaId));
                            area.setAreaName(areaNames[i]);
                            areas.add(area);
                        }
                        destination.addAreas(areas);
                        destinations.add(destination);
                    }
                    freightTempSub.addDestinations(destinations);
                }

                freightTempSubs.add(freightTempSub);
            }
            freightTemp.addFreightTempSubs(freightTempSubs);
        }
    }

    public FreightTempService getFreightTempService() {
        return freightTempService;
    }

    public void setFreightTempService(FreightTempService freightTempService) {
        this.freightTempService = freightTempService;
    }
}
